import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { size } from '@/app/utils';
import Events from './event';

interface ToastOptions {
    message?: string;
    callback?: () => void;
}

let Toast = () => {
    const [modalVisible, setModalVisible] = useState(false);
    const [toastText, setToastText] = useState('');

    // 使用 useCallback 包裹 _toast 函数，确保引用稳定
    const _toast = useCallback((options: string | ToastOptions) => {
        // 兼容入参为字符串或对象
        const opts = (options && typeof options === 'object') ? options : { message: String(options || '') };
        const text = opts.message ? opts.message : '服务异常！';

        setModalVisible(true);
        setToastText(text);

        // 延迟执行关闭逻辑
        setTimeout(() => {
            setModalVisible(false);
            setToastText('');

            // 使用本次传入的 opts，避免异步 state 导致回调丢失
            if (opts.callback && typeof opts.callback === 'function') {
                try { opts.callback(); } catch (_e) { }
            }
        }, 1000);
    }, [setModalVisible, setToastText]);

    // 注册和移除事件监听器
    useEffect(() => {
        Events.addListener('toast', _toast); // 添加事件监听
        return () => {
            Events.removeListener('toast', _toast); // 移除事件监听
        };
    }, [_toast]); // 将稳定的 _toast 函数加入依赖数组

    return (
        modalVisible ? (
            <View style={[styles.loading]}>
                <View style={styles.loadingbox}>
                    <Text style={styles.loadText}>{toastText}</Text>
                </View>
            </View>
        ) : null
    );
};

const styles = StyleSheet.create({
    loading: {
        position: 'absolute',
        left: 0,
        top: 0,
        right: 0,
        bottom: 0,
        zIndex: 9999999,
        elevation: 9999999,
        backgroundColor: 'rgba(0,0,0,0)',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
    },
    loadingbox: {
        backgroundColor: 'rgba(0,0,0,0.6)',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: size(6),
        maxWidth: size(300),
    },
    loadText: {
        color: '#ffffff',
        fontSize: size(14),
        padding: size(10),
    },
});

export default Toast;